//
//  SyncCertificateRequest.m
//  baovn
//
//  Created by Phuong Le on 2/20/14.
//  Copyright (c) 2014. All rights reserved.
//

#import "SyncCertificateRequest.h"

@implementation SyncCertificateRequest

- (id)initWithRequest:(NSURLRequest *)request callback:(void(^)(NSString *callbackData)) callback
{
    if (self = [super init])
    {
        self.lock = [ConsumerLock new];
        
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [NSURLConnection connectionWithRequest:request delegate:self];
            
            while(!self.lock.finished)
            {
                [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
            }
        });
        
        [self.lock consume:^(NSString *data) {
            if (callback != nil)
            {
                callback(data);
            }
        }];
    }
    
    return self;
}

+ (void)certificate:(NSURLRequest *)request callback:(void (^)(NSString *))callback
{
#ifndef __clang_analyzer__
    SyncCertificateRequest *connection;
    connection = [[SyncCertificateRequest alloc] initWithRequest:request callback:callback];
#endif
}

+ (BOOL)bypassSSLAuthenticationChallengeWithRequest:(NSURLRequest *)request
{
    __block NSString *_result = nil;
    [SyncCertificateRequest certificate:request callback:^(NSString *result)
     {
         _result = result;
     }];
    
    if ([_result isEqualToString:@"OK"] == NO)
    {
        return NO;
    }
    
    return YES;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    
    if ([httpResponse statusCode] == HTTP_REPONSE_OK)
    {
        [self.lock produce:@"OK"];
    }
    else
    {
        [self.lock produce:@"FAILED"];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [connection cancel];
    [self.lock finish];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [self.lock produce:@"FAILED"];
    [self.lock finish];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [self.lock finish];
}

@end
